<?php

// no direct access
defined('_JEXEC') or die('Restricted access');

require_once(JPATH_COMPONENT.DS.'classes'.DS.'article.php');

class YOS_Job extends JObject {
	//job id
	private $_id;
	
	//store component configuration
	private $_global_configure;
	
	//store all information fetched from jobs table.
	private $_job_configure;
				
	//a cms object
	private $_cms;
	
	//a link object which stores configurations to get an full article from remote site
	private $_link;
	
	//store list of recieved articles included text and images	
	private $_arr_articles;
	
	//get list of urls
	private function _get_list_urls()
	{
	}
	
	//get an article
	private function _get_articles()
	{
	}
	
	private function _get_cms()
	{
	}
	
	//update job info
	public function update_job()
	{
		$str_errors = '';
		if ($arr_error = $this->getErrors()) {
			foreach ($arr_error as $str_err){
				$str_errors .= '<div>'.$str_err.'</div>'."\n";
			}
		}
		
		$time_now		= JHTML::_('date','','%Y-%m-%d %H:%M:%S');
		$db	=& JFactory::getDBO();
		
		if ($str_errors) {
			//select current info
			$query = "SELECT `error_counter` FROM #__yos_news_crawler_jobs WHERE `id` = $this->_id";
			$db->setQuery($query);
			$current_errors = $db->loadResult();
			if ($db->getErrorNum()) {
				$arr_error = debug_backtrace();
				$this->setError('[JOB] MySQL error: '.$db->getErrorMsg()."\n FILE: ".$arr_error[0]['file']."\n LINE: ".$arr_error[0]['line']);
				return false;
			}
			if ($current_errors + 1 > $this->_global_configure->get('max_error')) {
				//unpublish job
				$str_ubpubilish_sql = "`published` = 0";
				//send an email notice administrators:
				$this->_send_mail($str_errors);
			}
			else {
				$str_ubpubilish_sql = "`published` = 1";
			}
			
			$query = "UPDATE #__yos_news_crawler_jobs SET 
				`last_update` = ".$db->Quote($time_now).", 
				`error_counter` = `error_counter` + 1, "
				.$str_ubpubilish_sql.", 
				`checked_out` = 0, 
				`error_msg` = CONCAT(`error_msg`, ".$db->Quote($str_errors).") 
				WHERE `id` = $this->_id";
		}
		else {
			$query = "UPDATE #__yos_news_crawler_jobs SET 
				`last_update` = ".$db->Quote($time_now).", 
				`checked_out` = 0, 
				`error_counter` = 0, 
				`error_msg` = '' 
				WHERE `id` = $this->_id";
		}
						
		$db->setQuery($query);
		$db->query();
		if ($db->getErrorNum()) {
			$arr_error = debug_backtrace();
			$this->setError('[JOB] MySQL error: '.$db->getErrorMsg()."\n FILE: ".$arr_error[0]['file']."\n LINE: ".$arr_error[0]['line']);
			return false;
		}
		return true;
	}
	
	private function _send_mail($str_errors){
		global $mainframe;
		$MailFrom	= $mainframe->getCfg('mailfrom');
		$FromName	= $mainframe->getCfg('fromname');
		$SiteName	= $mainframe->getCfg('sitename');
		
		$subject = JText::_('ERROR NEWS CRAWLER');
		$message = 'JOB ID: '.$this->_id."<br />\n";
		$message .= 'JOB NAME: '.$this->_job_configure->title."<br />\n";
		$message .= 'LAST ERROR MESSAGE: '.$str_errors;
		if (!JUtility::sendMail( $MailFrom, $FromName, $MailFrom, $subject, $message, 1 )) {
			$this->setError('Unable to send email.');
			return false;
		}
	}
	
	public function exec()
	{ 
		$yos_utility = new YOS_utility();
		
		//build article object
		if (JRequest::getInt('debug')) { YOS_utility::print_debug(2, "[JOB] init article object"); }
		$article = new YOS_Article($this->_job_configure->link_id, $this->_job_configure->cms, $this->_job_configure->keyword);
		if ($arr_errors = $article->getErrors()) {
			for ($i = 0; $i < count($arr_errors); $i++){
				$this->setError($arr_errors[$i]);
			}
			return false;
		}
		
		//get articles
		if (JRequest::getInt('debug')) { YOS_utility::print_debug(2, "[JOB] Get articles BEGIN"); }
		if ($article->do_get_articles() === false) {
			$arr_errors = $article->getErrors();
			for ($i = 0; $i < count($arr_errors); $i++){
				$this->setError($arr_errors[$i]);
			}
			$this->setError('[JOB] Fail to get articles.');
			return false;
		}		
		if (JRequest::getInt('debug')) { YOS_utility::print_debug(2, "[JOB] Get articles END"); }
		
		if (!count($article->get_articles())) {
			if (JRequest::getInt('debug')) { YOS_utility::print_debug(2, "[JOB] empty article"); }
			return true;
		}
		
		//translate
		if ($this->_job_configure->t_from && $this->_job_configure->t_to) {
			if (JRequest::getInt('debug')) { YOS_utility::print_debug(2, "[JOB] Translate articles BEGIN"); }
			if($article->do_translate($this->_job_configure->t_from, $this->_job_configure->t_to) === false){
				$arr_errors = $article->getErrors();
				for ($i = 0; $i < count($arr_errors); $i++){
					$this->setError($arr_errors[$i]);
				}
				$this->setError('[JOB] Fail to translate articles.');
				return false;
			}
			if (JRequest::getInt('debug')) { YOS_utility::print_debug(2, "[JOB] Translate articles END"); }
		}
		
		//TODO: rewrite? wee need a good rewiter engine.
		if ($this->_job_configure->rewrite) {
			
		}
		
		//using tidy to improve html code
		if( function_exists( 'tidy_parse_string' )) {
			if (JRequest::getInt('debug')) { YOS_utility::print_debug(2, "[JOB] Tidy clean BEGIN"); }
			if ($article->do_tidy_clean() === false) {
				$arr_errors = $article->getErrors();
				for ($i = 0; $i < count($arr_errors); $i++){
					$this->setError($arr_errors[$i]);
				}
				$this->setError('[JOB] Fail to do tidy clean.');
				return false;
			}
			if (JRequest::getInt('debug')) { YOS_utility::print_debug(2, "[JOB] Tidy clean END"); }
		}
		
		//get images and resize them
		if (JRequest::getInt('debug')) { YOS_utility::print_debug(2, "[JOB] get & resize images BEGIN"); }
		if ($this->_job_configure->get_img) {
			$max_width = 0; $max_height = 0;
			if ($this->_job_configure->resizeimage) {
				$max_width = $this->_job_configure->images_max_width;
				$max_height = $this->_job_configure->images_max_height;
			}
			if($article->do_fetch_images($max_width, $max_height) === false){
				$arr_errors = $article->getErrors();
				for ($i = 0; $i < count($arr_errors); $i++){
					$this->setError($arr_errors[$i]);
				}
				return false;
			}
		}
		if (JRequest::getInt('debug')) { YOS_utility::print_debug(2, "[JOB] get & resize images END"); }
				
		$this->_arr_articles = $article->get_articles();
		
		if (!count($this->_arr_articles)) {
			if (JRequest::getInt('debug')) { YOS_utility::print_debug(2, "[JOB] empty article #2"); }
			return true;
		}
		
		//long time no connect, try to check mysql connection;
		$yos_utility->mysql_check_connection();
		
		//build cms object
		if (JRequest::getInt('debug')) { YOS_utility::print_debug(2, "[JOB] build CMS object"); }
		$cms_name = $this->_job_configure->cms;
		$cms_path = JPATH_COMPONENT_SITE.DS.'cms'.DS.$cms_name;
		if(!is_readable($cms_path.DS.$cms_name.'.php')){
			$this->setError('[JOB] CMS file is not exist: '.$cms_path.DS.$cms_name.'.php');
			return false;
		}
		require_once($cms_path.DS.$cms_name.'.php');
		$cms_class = 'YOS_Cms_'.ucfirst($cms_name);
		if(!class_exists($cms_class)){
			$this->setError('[JOB] unable to load CMS: '.$cms_name);
			return false;
		}
		$CMS = new $cms_class($this->_job_configure, $this->_arr_articles);
	
		//call cms store article
		if (JRequest::getInt('debug')) { YOS_utility::print_debug(2, "[JOB] ask CMS object to store articles BEGIN"); }
		$CMS->store_articles();
		if ($arr_errors = $CMS->getErrors()) {
			for ($i = 0; $i < count($arr_errors); $i++){
				$this->setError($arr_errors[$i]);
			}
			return false;
		}
		if (JRequest::getInt('debug')) { YOS_utility::print_debug(2, "[JOB] ask CMS object to store articles END"); }
		
		return true;
	}
	
	public function __construct($id)
	{			
		$db	=& JFactory::getDBO();
		$query="SELECT * 
				FROM `#__yos_news_crawler_jobs` 
				WHERE `id` = $id";
		$db->setQuery($query);
		$job_info = $db->loadObject();
		
		
		// check in job. 	
		$now	= JHTML::_('date','','%Y-%m-%d %H:%M:%S');
		$now = strtotime($now) + $job_info->time_update * 60;
		$date = JFactory::getDate($now);	
		
		$this->set('checked_out_time',$date->toMySQL());
		$query	=	'UPDATE `#__yos_news_crawler_jobs`  
						SET `checked_out` = 1, 
							`checked_out_time`='.$db->Quote($date->toMySQL()).'
							WHERE `id` ='.$id;
		$db->setQuery($query);
		$db->Query();
		
		
		if ($db->getErrorNum()) {
			$arr_error = debug_backtrace();
			$this->setError('[JOB] MySQL error: '.$db->getErrorMsg()."\n FILE: ".$arr_error[0][0]['file']."\n LINE: ".$arr_error[0][0]['line']);
			return false;
		}
		if (!$job_info) {
			$this->setError('[JOB] Job not found: '. $id);
			return ;
		}
		
		$this->_id = $id;
		$this->_job_configure = $job_info;
		
		$config = &JComponentHelper::getParams('com_yos_news_crawler');
		$this->_global_configure = $config;		
	}
	
	public function get_job_title(){
		return $this->_job_configure->title;
	}
}